<template>
  <div class="app-container">
    <el-form ref="articleForm" :model="article" :rules="articleFormRule" label-width="120px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="article.title" maxlength="100" show-word-limit clearable />
      </el-form-item>
      <el-form-item label="是否展示">
        <el-switch v-model="article.enabled" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="是否允许评论">
        <el-switch v-model="article.isAllowComment" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="是否允许点赞">
        <el-switch v-model="article.isAllowPraise" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="标签选择">
        <el-tag
          v-for="tag in article.tags"
          :key="tag.id"
          effect="dark"
          closable
          :disable-transitions="false"
          :hit="true"
          @close="handleClose(tag)"
        >
          {{ tag.name }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="saveTagInput"
          v-model="inputValue"
          class="input-new-tag"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
      </el-form-item>
      <el-form-item label="封面图" prop="image">
        <el-upload
          ref="upload"
          class="avatar-uploader"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
          :data-id="article.id || 0"
          action="https://jsonplaceholder.typicode.com/posts/"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="概述">
        <el-input v-model="article.description" :autosize="{ minRows: 4, maxRows: 6}" type="textarea" placeholder="请输入概述..." maxlength="250" show-word-limit />
      </el-form-item>
      <el-form-item label="内容" class="editor" prop="content">
        <mavon-editor
          ref="md"
          v-model="article.content"
          placeholder="请输入你的内容..."
          :code-style="mavonEditor.code_style"
          @change="mavonChange"
          @save="mavonSave"
          @imgAdd="$imgAdd"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAddOrUpdate(true)">保存</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getArticle, addOrUpdate } from '@/api/article'
import { mavonEditor } from 'mavon-editor'
import { upload } from '@/api/support'

export default {
  components: {
    mavonEditor
  },
  data() {
    return {
      articleFormRule: {
        title: { required: true, message: '请给我起个帅气的名字', trigger: 'change' },
        image: { required: true, message: '我也需要脸，请给我上传张封面图', trigger: 'change' },
        content: { required: true, message: '请为我编写一些华丽的内容', trigger: 'change' }
      },
      articleId: 0,
      article: {
        title: '',
        image: '',
        content: ``,
        enabled: 0,
        description: '',
        tags: []
      },
      imageUrl: '',
      dynamicTags: [{
        id: 1,
        name: '标签一'
      }],
      inputVisible: false,
      inputValue: '',
      content: ``,
      mavonEditor: {
        code_style: 'atom-one-dark',
        navigation: true
      }
    }
  },
  watch: {
    'article.image': function(newImage) {
      if (newImage.indexOf('http') > -1) {
        this.imageUrl = newImage
      }
    },
    'article.tags': function(newCurrent) {
      if (newCurrent === undefined) {
        this.article.tags = []
      }
    }
  },
  created() {
    this.getArticleId()
    this.getData()
  },
  methods: {
    // 获取路由携带的文章Id
    getArticleId() {
      this.articleId = this.$route.query.id
    },
    // 请求文章数据
    getData() {
      if (this.articleId !== undefined) {
        getArticle(this.articleId).then(response => {
          if (response.code === 200) {
            this.article = response.data
          } else {
            this.$notify({
              title: '请求失败',
              message: response.message,
              type: 'error',
              duration: 2000
            })
          }
        })
      }
    },
    onCancel() {
      this.$router.go(-1)
    },
    // 添加或更新文章
    handleAddOrUpdate(isRouter) {
      this.$refs.articleForm.validate((valid) => {
        if (valid) {
          addOrUpdate(this.article).then(response => {
            if (response.code === 200) {
              if (isRouter) {
                this.$router.push('/article/index')
              }
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '请求失败',
                message: response.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: '输入有误，请重新检查'
          })
          return false
        }
      })
    },
    // 绑定@imgAdd event
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formData = new FormData()
      formData.append('files', $file)
      formData.append('objectId', 'new')
      formData.append('code', 1)
      upload(formData).then(response => {
        if (response.code === 200) {
          this.$refs.md.$img2Url(pos, response.data.domain + response.data.url)
          this.$notify({
            title: '成功',
            message: '上传成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    // 上传成功
    handleUploadSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.article.image = this.imageUrl
      this.handleUpload(file)
    },
    // 上传之前判断是否是图片
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传文件，获取文件流
    handleUpload(file) {
      const raw = file.raw
      const formData = new FormData()
      formData.append('objectId', this.$refs.upload.$el.getAttribute('data-id'))
      formData.append('code', 1)
      formData.append('files', raw)
      upload(formData).then(response => {
        if (response.code === 200) {
          this.article.image = response.data.url
          this.$notify({
            title: '成功',
            message: '上传成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    /** 标签 */
    handleClose(tag) {
      this.article.tags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.article.tags.push({ name: inputValue })
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    /** mavonEditor */
    // 改变
    mavonChange(value, render) {
      // console.log(value)
      // console.log(marked(render))
    },
    // 保存
    mavonSave(value, render) {
      this.handleAddOrUpdate(false)
    }
  }
}
</script>

<style>
  .el-form {
    padding-right: 6%;
  }

  .markdown-body {
    height: 450px;
  }

  /** 上传图片*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin-top: 14px;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    background-color: #fff
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  /** 标签 */
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  /** 解决element行高导致副本本下拉框高度问题 */
  .editor .el-form-item__content {
    line-height: normal;
    background-color: #ffff;
  }

  pre, code {
    font-family: Consolas;
  }

  .ql-snow .ql-editor pre.ql-syntax {
    background-color: #282b2e
  }

  .ql-container {
    height: 500px;
  }
</style>

